package com.taa.domain.trade.service.chain.impl;

import com.taa.domain.trade.adapter.repository.ITradeRepository;
import com.taa.domain.trade.service.chain.AbstractValidationChain;
import com.taa.types.enums.ResponseCode;
import com.taa.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: taa
 * @Desc: 库存责任链
 * @Create: 2025-06-01 20:15
 **/
@Slf4j
@Component("stock")
public class StockValidationChain extends AbstractValidationChain {
    
    @Resource
    private ITradeRepository repository;
    
    @Override
    public boolean validate(String userName, List<Long> productIdList) {
        log.info("库存责任链校验 userName: {} productId: {}", userName, productIdList);
        for (Long productId : productIdList) {
            int stock = repository.queryStockByProductId(productId);
            if (stock < 0) {
                log.info("库存责任链校验失败 userName: {} productId: {}", userName, productIdList);
                throw new AppException(ResponseCode.STOCK_EMPTY.getCode(), ResponseCode.STOCK_EMPTY.getInfo());
            }
        }
        log.info("库存责任链校验成功 userName: {} productId: {}", userName, productIdList);
        return next().validate(userName, productIdList);
    }
}

